/**
 * 活动类型管理页面JavaScript
 * 基于Apple Design System的交互设计
 * 版本：v1.0
 * 创建时间：2025-07-20
 */

// 全局变量
let activityTypes = [];
let customTypes = [];
let currentEditingType = null;
let isEditMode = false;

// DOM 元素
const addActivityTypeBtn = document.getElementById('add-activity-type-btn');
const customTypesGrid = document.getElementById('custom-types-grid');
const emptyState = document.getElementById('empty-state');
const activityTypeModal = document.getElementById('activity-type-modal');
const modalTitle = document.getElementById('modal-title');
const activityTypeForm = document.getElementById('activity-type-form');

// 页面初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeEventListeners();
    loadActivityTypes();
    loadCustomTypes();
    updateCustomTypesDisplay();
});

// 初始化事件监听器
function initializeEventListeners() {
    // 新增类型按钮
    addActivityTypeBtn.addEventListener('click', openAddTypeModal);
    
    // 图标选择器
    initializeIconSelector();
    
    // 模态框事件
    document.addEventListener('click', handleModalClick);
    document.addEventListener('keydown', handleKeyDown);
    
    // 表单验证
    initializeFormValidation();
    
    // 成本计算
    initializeCostCalculation();
}

// 初始化图标选择器
function initializeIconSelector() {
    const iconBtns = document.querySelectorAll('.icon-btn');
    const selectedIconInput = document.getElementById('selected-icon');
    
    iconBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            // 移除其他按钮的活动状态
            iconBtns.forEach(b => b.classList.remove('active'));
            
            // 设置当前按钮为活动状态
            this.classList.add('active');
            
            // 更新隐藏输入值
            selectedIconInput.value = this.dataset.icon;
        });
    });
}

// 初始化表单验证
function initializeFormValidation() {
    const typeNameInput = document.getElementById('type-name');
    const minParticipantsInput = document.getElementById('min-participants');
    const maxParticipantsInput = document.getElementById('max-participants');
    
    typeNameInput.addEventListener('input', validateTypeName);
    minParticipantsInput.addEventListener('input', validateParticipantRange);
    maxParticipantsInput.addEventListener('input', validateParticipantRange);
}

// 初始化成本计算
function initializeCostCalculation() {
    const estimatedCostInput = document.getElementById('estimated-cost');
    const minParticipantsInput = document.getElementById('min-participants');
    const maxParticipantsInput = document.getElementById('max-participants');
    const costPerPersonInput = document.getElementById('cost-per-person');
    
    function calculateCostPerPerson() {
        const estimatedCost = parseFloat(estimatedCostInput.value) || 0;
        const minParticipants = parseInt(minParticipantsInput.value) || 0;
        const maxParticipants = parseInt(maxParticipantsInput.value) || 0;
        
        if (estimatedCost > 0 && minParticipants > 0 && maxParticipants > 0) {
            const avgParticipants = (minParticipants + maxParticipants) / 2;
            const costPerPerson = Math.round(estimatedCost / avgParticipants);
            costPerPersonInput.value = costPerPerson;
        } else {
            costPerPersonInput.value = '';
        }
    }
    
    estimatedCostInput.addEventListener('input', calculateCostPerPerson);
    minParticipantsInput.addEventListener('input', calculateCostPerPerson);
    maxParticipantsInput.addEventListener('input', calculateCostPerPerson);
}

// 加载活动类型数据
function loadActivityTypes() {
    // 模拟预设活动类型数据
    activityTypes = [
        {
            id: 'preset-1',
            name: '产品推介会',
            description: '新线路产品发布和介绍',
            icon: 'fas fa-presentation',
            duration: 120,
            minParticipants: 50,
            maxParticipants: 100,
            venueRequirements: '需要投影设备、音响设备、展示台',
            estimatedCost: 8000,
            expectedConversion: 25,
            type: 'preset',
            category: 'offline',
            status: 'active'
        },
        {
            id: 'preset-2',
            name: '目的地分享会',
            description: '特定目的地的深度介绍',
            icon: 'fas fa-map-marked-alt',
            duration: 90,
            minParticipants: 30,
            maxParticipants: 60,
            venueRequirements: '需要投影设备、音响设备',
            estimatedCost: 5000,
            expectedConversion: 30,
            type: 'preset',
            category: 'offline',
            status: 'active'
        }
        // 更多预设类型...
    ];
}

// 加载自定义类型
function loadCustomTypes() {
    // 模拟自定义活动类型数据
    customTypes = [
        {
            id: 'custom-1',
            name: '康养主题分享会',
            description: '专注于健康养生的旅游产品分享',
            icon: 'fas fa-spa',
            duration: 100,
            minParticipants: 20,
            maxParticipants: 40,
            venueRequirements: '安静环境，需要投影设备',
            estimatedCost: 4000,
            expectedConversion: 40,
            type: 'custom',
            status: 'active',
            createdAt: '2025-07-15',
            updatedAt: '2025-07-20'
        }
    ];
}

// 更新自定义类型显示
function updateCustomTypesDisplay() {
    if (customTypes.length === 0) {
        customTypesGrid.style.display = 'none';
        emptyState.style.display = 'flex';
    } else {
        customTypesGrid.style.display = 'grid';
        emptyState.style.display = 'none';
        renderCustomTypes();
    }
}

// 渲染自定义类型
function renderCustomTypes() {
    // 清除现有内容
    const existingCards = customTypesGrid.querySelectorAll('.type-card.custom');
    existingCards.forEach(card => card.remove());
    
    // 渲染自定义类型卡片
    customTypes.forEach(type => {
        const card = createTypeCard(type);
        customTypesGrid.appendChild(card);
    });
}

// 创建类型卡片
function createTypeCard(type) {
    const card = document.createElement('div');
    card.className = 'type-card custom';
    card.dataset.typeId = type.id;
    
    const participantRange = type.maxParticipants ? 
        `${type.minParticipants}-${type.maxParticipants}人` : 
        `${type.minParticipants}人以上`;
    
    card.innerHTML = `
        <div class="card-header">
            <div class="type-icon custom-icon">
                <i class="${type.icon}"></i>
            </div>
            <div class="type-status">
                <span class="status-badge ${type.status === 'active' ? 'status-active' : 'status-inactive'}">
                    ${type.status === 'active' ? '启用' : '禁用'}
                </span>
            </div>
        </div>
        <div class="card-body">
            <h4 class="type-name">${type.name}</h4>
            <p class="type-description">${type.description || '暂无描述'}</p>
            <div class="type-details">
                <div class="detail-item">
                    <span class="detail-label">默认时长</span>
                    <span class="detail-value">${type.duration}分钟</span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">适合人数</span>
                    <span class="detail-value">${participantRange}</span>
                </div>
                <div class="detail-item">
                    <span class="detail-label">转化预期</span>
                    <span class="detail-value">${type.expectedConversion}%</span>
                </div>
            </div>
        </div>
        <div class="card-footer">
            <button class="btn btn-outline btn-small" onclick="editActivityType('${type.id}')">
                <i class="fas fa-edit"></i>
                编辑
            </button>
            <button class="btn btn-destructive btn-small" onclick="deleteActivityType('${type.id}')">
                <i class="fas fa-trash"></i>
                删除
            </button>
        </div>
    `;
    
    return card;
}

// 打开新增类型模态框
function openAddTypeModal() {
    isEditMode = false;
    currentEditingType = null;
    modalTitle.textContent = '新增活动类型';
    
    // 重置表单
    activityTypeForm.reset();
    
    // 重置图标选择
    const iconBtns = document.querySelectorAll('.icon-btn');
    iconBtns.forEach(btn => btn.classList.remove('active'));
    iconBtns[0].classList.add('active');
    document.getElementById('selected-icon').value = iconBtns[0].dataset.icon;
    
    // 显示模态框
    activityTypeModal.classList.add('show');
    
    // 聚焦到第一个输入框
    setTimeout(() => {
        document.getElementById('type-name').focus();
    }, 300);
}

// 编辑活动类型
function editActivityType(typeId) {
    isEditMode = true;
    currentEditingType = typeId;
    modalTitle.textContent = '编辑活动类型';
    
    // 查找类型数据
    let typeData = null;
    if (typeId.startsWith('preset-')) {
        typeData = activityTypes.find(t => t.id === typeId);
    } else {
        typeData = customTypes.find(t => t.id === typeId);
    }
    
    if (!typeData) {
        showNotification('未找到活动类型数据', 'error');
        return;
    }
    
    // 填充表单数据
    fillFormWithTypeData(typeData);
    
    // 显示模态框
    activityTypeModal.classList.add('show');
}

// 填充表单数据
function fillFormWithTypeData(typeData) {
    document.getElementById('type-name').value = typeData.name;
    document.getElementById('type-description').value = typeData.description || '';
    document.getElementById('default-duration').value = typeData.duration || '';
    document.getElementById('min-participants').value = typeData.minParticipants || '';
    document.getElementById('max-participants').value = typeData.maxParticipants || '';
    document.getElementById('venue-requirements').value = typeData.venueRequirements || '';
    document.getElementById('expected-conversion').value = typeData.expectedConversion || '';
    document.getElementById('estimated-cost').value = typeData.estimatedCost || '';
    
    // 设置图标选择
    const iconBtns = document.querySelectorAll('.icon-btn');
    iconBtns.forEach(btn => {
        btn.classList.toggle('active', btn.dataset.icon === typeData.icon);
    });
    document.getElementById('selected-icon').value = typeData.icon;
    
    // 触发成本计算
    const costEvent = new Event('input');
    document.getElementById('estimated-cost').dispatchEvent(costEvent);
}

// 删除活动类型
function deleteActivityType(typeId) {
    if (typeId.startsWith('preset-')) {
        showNotification('系统预设类型不能删除，只能编辑配置', 'warning');
        return;
    }
    
    if (confirm('确定要删除这个活动类型吗？此操作不可撤销。')) {
        // 从数组中移除
        customTypes = customTypes.filter(t => t.id !== typeId);
        
        // 更新显示
        updateCustomTypesDisplay();
        
        showNotification('活动类型已删除', 'success');
    }
}

// 保存活动类型
function saveActivityType() {
    // 验证表单
    if (!validateForm()) {
        return;
    }
    
    // 收集表单数据
    const formData = collectFormData();
    
    if (isEditMode && currentEditingType) {
        // 编辑模式
        updateActivityType(currentEditingType, formData);
    } else {
        // 新增模式
        createActivityType(formData);
    }
}

// 验证表单
function validateForm() {
    let isValid = true;
    
    // 验证类型名称
    const typeName = document.getElementById('type-name').value.trim();
    if (!typeName) {
        showFieldError('type-name', '请输入类型名称');
        isValid = false;
    } else {
        clearFieldError('type-name');
    }
    
    // 验证参与人数范围
    const minParticipants = parseInt(document.getElementById('min-participants').value);
    const maxParticipants = parseInt(document.getElementById('max-participants').value);
    
    if (minParticipants && maxParticipants && minParticipants >= maxParticipants) {
        showFieldError('max-participants', '最大人数必须大于最小人数');
        isValid = false;
    } else {
        clearFieldError('max-participants');
    }
    
    return isValid;
}

// 收集表单数据
function collectFormData() {
    return {
        name: document.getElementById('type-name').value.trim(),
        description: document.getElementById('type-description').value.trim(),
        icon: document.getElementById('selected-icon').value,
        duration: parseInt(document.getElementById('default-duration').value) || null,
        minParticipants: parseInt(document.getElementById('min-participants').value) || null,
        maxParticipants: parseInt(document.getElementById('max-participants').value) || null,
        venueRequirements: document.getElementById('venue-requirements').value.trim(),
        expectedConversion: parseFloat(document.getElementById('expected-conversion').value) || null,
        estimatedCost: parseFloat(document.getElementById('estimated-cost').value) || null
    };
}

// 创建活动类型
function createActivityType(formData) {
    const newType = {
        id: `custom-${Date.now()}`,
        ...formData,
        type: 'custom',
        status: 'active',
        createdAt: new Date().toISOString().split('T')[0],
        updatedAt: new Date().toISOString().split('T')[0]
    };
    
    customTypes.push(newType);
    updateCustomTypesDisplay();
    closeActivityTypeModal();
    showNotification('活动类型创建成功！', 'success');
}

// 更新活动类型
function updateActivityType(typeId, formData) {
    if (typeId.startsWith('preset-')) {
        // 更新预设类型
        const typeIndex = activityTypes.findIndex(t => t.id === typeId);
        if (typeIndex !== -1) {
            activityTypes[typeIndex] = { ...activityTypes[typeIndex], ...formData };
            showNotification('活动类型配置已更新！', 'success');
        }
    } else {
        // 更新自定义类型
        const typeIndex = customTypes.findIndex(t => t.id === typeId);
        if (typeIndex !== -1) {
            customTypes[typeIndex] = { 
                ...customTypes[typeIndex], 
                ...formData,
                updatedAt: new Date().toISOString().split('T')[0]
            };
            updateCustomTypesDisplay();
            showNotification('活动类型已更新！', 'success');
        }
    }
    
    closeActivityTypeModal();
}

// 关闭模态框
function closeActivityTypeModal() {
    activityTypeModal.classList.remove('show');
    
    // 清理状态
    isEditMode = false;
    currentEditingType = null;
    
    // 清除表单验证状态
    clearAllFieldErrors();
}

// 表单验证函数
function validateTypeName() {
    const input = document.getElementById('type-name');
    const value = input.value.trim();
    
    if (!value) {
        showFieldError('type-name', '请输入类型名称');
        return false;
    } else if (value.length < 2) {
        showFieldError('type-name', '类型名称至少需要2个字符');
        return false;
    } else {
        clearFieldError('type-name');
        return true;
    }
}

function validateParticipantRange() {
    const minInput = document.getElementById('min-participants');
    const maxInput = document.getElementById('max-participants');
    const minValue = parseInt(minInput.value);
    const maxValue = parseInt(maxInput.value);
    
    if (minValue && maxValue && minValue >= maxValue) {
        showFieldError('max-participants', '最大人数必须大于最小人数');
        return false;
    } else {
        clearFieldError('max-participants');
        return true;
    }
}

// 显示字段错误
function showFieldError(fieldId, message) {
    const field = document.getElementById(fieldId);
    field.classList.add('error');
    
    // 移除现有错误消息
    const existingError = field.parentNode.querySelector('.error-message');
    if (existingError) {
        existingError.remove();
    }
    
    // 添加错误消息
    const errorDiv = document.createElement('div');
    errorDiv.className = 'error-message';
    errorDiv.textContent = message;
    field.parentNode.appendChild(errorDiv);
}

// 清除字段错误
function clearFieldError(fieldId) {
    const field = document.getElementById(fieldId);
    field.classList.remove('error');
    
    const errorMessage = field.parentNode.querySelector('.error-message');
    if (errorMessage) {
        errorMessage.remove();
    }
}

// 清除所有字段错误
function clearAllFieldErrors() {
    const errorInputs = document.querySelectorAll('.form-input.error');
    errorInputs.forEach(input => {
        input.classList.remove('error');
    });
    
    const errorMessages = document.querySelectorAll('.error-message');
    errorMessages.forEach(message => {
        message.remove();
    });
}

// 返回活动列表
function goBackToActivityList() {
    window.location.href = 'invitation-management.html';
}

// 通用函数
function handleModalClick(event) {
    if (event.target.classList.contains('modal-overlay')) {
        closeActivityTypeModal();
    }
}

function handleKeyDown(event) {
    if (event.key === 'Escape') {
        closeActivityTypeModal();
    }
}

function showNotification(message, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `alert alert-${type}`;
    notification.innerHTML = `
        <i class="fas fa-${getNotificationIcon(type)}"></i>
        <span>${message}</span>
    `;
    
    // 添加到页面
    document.body.appendChild(notification);
    
    // 定位
    notification.style.position = 'fixed';
    notification.style.top = '80px';
    notification.style.right = '20px';
    notification.style.zIndex = '9999';
    notification.style.minWidth = '300px';
    notification.style.animation = 'slideInRight 0.3s ease-out';
    
    // 自动移除
    setTimeout(() => {
        notification.style.animation = 'slideOutRight 0.3s ease-in';
        setTimeout(() => {
            if (document.body.contains(notification)) {
                document.body.removeChild(notification);
            }
        }, 300);
    }, 3000);
}

function getNotificationIcon(type) {
    const iconMap = {
        'info': 'info-circle',
        'success': 'check-circle',
        'warning': 'exclamation-triangle',
        'error': 'times-circle'
    };
    return iconMap[type] || 'info-circle';
}

// 导出函数供HTML使用
window.editActivityType = editActivityType;
window.deleteActivityType = deleteActivityType;
window.openAddTypeModal = openAddTypeModal;
window.closeActivityTypeModal = closeActivityTypeModal;
window.saveActivityType = saveActivityType;
window.goBackToActivityList = goBackToActivityList;